package com.qdlc.p2p.biz.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.qdlc.p2p.biz.executer.AbstractExecuter;
import com.qdlc.p2p.biz.executer.ExecuterHelper;
import com.qdlc.p2p.biz.executer.impl.BondAddNoticeExecuter;
import com.qdlc.p2p.biz.executer.impl.BondSellStopNoticeExecuter;
import com.qdlc.p2p.biz.service.BondService;
import com.qdlc.p2p.common.constant.BondStatus;
import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.exception.BondException;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.OrderNoUtil;
import com.qdlc.p2p.dal.checkrule.BondConfigRuleCheck;
import com.qdlc.p2p.dal.common.RuleCheckHelper;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dao.BondDao;
import com.qdlc.p2p.dal.dao.BondTenderDao;
import com.qdlc.p2p.dal.dao.BorrowCollectionDao;
import com.qdlc.p2p.dal.dao.BorrowTenderDao;
import com.qdlc.p2p.dal.dto.*;
import com.qdlc.p2p.dal.model.BondModel;

/**
 * 债权Service
 *
 * @author zhangyz
 * @version 1.0
 * @since 2014-12-11
 */
@Service(value = "bondService")
@Transactional
public class BondServiceImpl implements BondService {

    @Resource
    private BondDao bondDao;

    @Resource
    private BondTenderDao bondTenderDao;

    @Resource
    private BorrowTenderDao borrowTenderDao;

    @Resource
    private BorrowCollectionDao borrowCollectionDao;

    @Override
    public Bond addBond(Bond bond) {

        Date nowDate = DateUtil.getNow();
        bond.setDayId(bondDao.getMaxDayId(DateUtil.dateStr7(nowDate)) + 1);
        // 跳过初审
        BondConfigRuleCheck bondConfigRuleCheck = RuleCheckHelper.getValue(BondConfigRuleCheck.class);
        if (bondConfigRuleCheck.bondNeedVerify == 0) {
            bond.setStatus(BondStatus.STATUS_VERIFY_SUCC);
        } else {
            bond.setStatus(BondStatus.STATUS_RELEASE);
        }
        // 下一期还款
        BorrowTender borrowTender = borrowTenderDao.find(bond.getBorrowTenderId()); //获得最初发布人的userId
        BorrowCollection nextBorrowCollection = borrowCollectionDao.getNextCollectionByBorrowId(bond.getBorrow().getId(), borrowTender.getUser().getUserId());
        String uuid = OrderNoUtil.getInstance().getSerialNumber();
        bond.setUuid(uuid);
        bond.setStartPeriod(nextBorrowCollection.getPeriod());
        bond.setVerifyUserId(1);
        bond.setVerifyTime(nowDate);
        bond.setFullVerifyUserId(1);
        bond.setFullVerifyTime(nowDate);
        bond.setAddTime(nowDate);
        bondDao.save(bond);

        // 给债权出让人发送发布债权成功通知
        Global.setTransfer("bond", bond);
        Global.setTransfer("user", bond.getUser());
        AbstractExecuter bondAddNoticeExecuter = ExecuterHelper.getExecuter(BondAddNoticeExecuter.class);
        bondAddNoticeExecuter.execute(0, bond.getUser());
        return bond;
    }


    @Override
    public Bond find(String uuid) {
        return bondDao.find(uuid);
    }

    @Override
    public BondModel getBondDetail(BondModel model) {

        PageDataList<BondModel> pageList = bondDao.getBondList(model);

        List<BondModel> list = pageList.getList();

        if (list != null && list.size() > 0) {
            return list.get(0);
        } else {
            throw new BondException("债权不存在！");
        }
    }

    @Override
    public PageDataList<BondModel> getBondList(BondModel model) {
        return bondDao.getBondList(model);
    }

    @Override
    public PageDataList<BondModel> getBondModelPage(BondModel model) {
        return bondDao.getBondModelPage(model);
    }

    @Override
    public PageDataList<BondModel> getSellingBondList(BondModel model) {
        return bondDao.getSellingBondList(model);
    }

    @Override
    public PageDataList<BondModel> getSoldBondList(BondModel model) {
        return bondDao.getSoldBondList(model);
    }

    @Override
    public void stopBond(long bondId) {
        Bond bond = bondDao.getBondById(bondId);
        if (bond.getStatus() != BondStatus.STATUS_VERIFY_SUCC) {
            throw new BondException("债权撤回失败！");
        }
        bond.setStatus(BondStatus.STATUS_STOP_USER);
        bondDao.update(bond);

        // 债权撤回时给债权出让人发送通知
        Global.setTransfer("user", bond.getUser());
        AbstractExecuter repayExecuter = ExecuterHelper.getExecuter(BondSellStopNoticeExecuter.class);
        repayExecuter.execute(0, bond.getUser());

    }

    @Override
    public BondModel getBondModelByBondId(String uuid) {
        Bond bond = bondDao.find(uuid);
        BondModel bondModel = new BondModel();
        Borrow borrow = bond.getBorrow();
        bondModel.setBorrowName(borrow.getName());
        bondModel.setApr(borrow.getApr());
        bondModel.setTenderMoney(borrowTenderDao.find(bond.getBorrowTenderId()).getMoney());
        bondModel.setHoldDays(DateUtil.daysBetween(borrow.getReviewTime(), DateUtil.getNow()));
        bondModel.setReviewTime(borrow.getReviewTime());
        bondModel.setLastRepaymentTime(borrowCollectionDao.getLastRepayDateByBorrowId(borrow.getId()));
        bondModel.setBorrowStyle(borrow.getStyle());
        return bondModel;
    }

    @Override
    public BondModel getBondModelByBondId(long id) {
        Bond bond = bondDao.find(id);
        BondModel bondModel = BondModel.instance(bond);
        Borrow borrow = bond.getBorrow();
        bondModel.setBorrowName(borrow.getName());
        bondModel.setBorrowId(borrow.getId());
        bondModel.setApr(borrow.getApr());
        bondModel.setTenderMoney(borrowTenderDao.find(bond.getBorrowTenderId()).getMoney());
        bondModel.setHoldDays(DateUtil.daysBetween(borrow.getReviewTime(), DateUtil.getNow()));
        bondModel.setReviewTime(borrow.getReviewTime());
        bondModel.setLastRepaymentTime(borrowCollectionDao.getLastRepayDateByBorrowId(borrow.getId()));
        bondModel.setBorrowStyle(borrow.getStyle());
        return bondModel;
    }

    @Override
    public BondModel getBondModelByBondTenderId(long tenderId) {

        BondTender bondTender = bondTenderDao.getBondTenderById(tenderId);
        Bond bond = bondTender.getBond();

        BondModel bondModel = new BondModel();
        Borrow borrow = bond.getBorrow();
        bondModel.setBorrowName(borrow.getName());
        bondModel.setBorrowId(borrow.getId());
        bondModel.setApr(borrow.getApr());
        bondModel.setTenderMoney(bondTender.getTenderMoney());
        Date lastDay = borrowCollectionDao.getLastRepayDateByBorrowId(borrow.getId());
        bondModel.setReviewTime(borrow.getReviewTime());
        bondModel.setRemainDays(DateUtil.daysBetween(DateUtil.getNow(), lastDay));
        bondModel.setLastRepaymentTime(lastDay);
        bondModel.setBorrowStyle(borrow.getStyle());
        return bondModel;
    }
}
